package system
/**
 * 角色
 */
class Role {
    /*角色名称*/
    String name;
    /*描述*/
    String remark
    /*简拼*/
    String jianpin
    /** 创建时间 */
    Date dateCreated
    /** 最后更新的时间 */
    Date lastUpdated
    static hasMany = [staffMemberRole: StaffMemberRole, roleAuthority: RoleAuthority]  //多个权限  ,
    static transients = ['staffMember']
    static constraints = {
        remark(nullable: true)
        name unique: true
        jianpin unique: true
    }
    static mapping = {

    }
    String toString() {
        name
    }
    List<StaffMember> getStaffMember(){
        return this.staffMemberRole?.staffMember?.flatten()
    }
    //2012-2-22 fang update 删除一个角色
    //实现: 1.解除所有用户与该角色的关联 2. 删除角色
    static deleteRole(Role role) {
        //先移除该权限分配到每一个用户独有的权限   ,共有的不能删除
        def staffmenberList = role.staffMember;   //与该角色关联的用户
        def temList = []  //中转list
        staffmenberList.each {
            temList << it
        }

        temList.each {

            it.delRole(role)     //1
        }
        role.delete()    //2
    }

    static removeAuthority(Role role, Authority authority) {
        def staffmenberList = role.staffMember;
        def authorityList = role.roleAuthority?.authority?.id    //该角色对应的权限

        staffmenberList.each {
            def boo = true//该权限是否能移除与it用户的关联
            def authorityList2 = []
            def otherRoles = it?.role.flatten() - [role]
            otherRoles.each {
                authorityList2 << it.roleAuthority.authority.id.flatten()
            }
            authorityList2 = authorityList2.flatten()
            boo = !(authorityList2.contains(authority.id))
//            println("authorityList2 "+authorityList2+" authority.id-->"+authority.id+" boo-->"+boo)
            if (boo) {
                StaffMemberAuthority.remove(it, authority, true)
            }
        }
        //移除 该角色与该权限的关联
        if (authority)
            RoleAuthority.remove(role, authority, true)
    }

    //2012-2-22 fang add 取得某一角色的权限
    static List<Authority> getAuthoritys(Role role) {
        return role.roleAuthority.authority
    }


    def utilsService

    def buildDomain() {
        def b = [:] + this.properties
        b.remove('roleAuthority')
        b = utilsService.truncProp(this,b) { amap ->
            amap << ['id': this?.id]
        }
        b
    }

    def buildDomainList(list) {
        def rds = []
        list.each {
            def b = [:] + it?.properties
            def that=it
            b = utilsService.truncProp(that,b) { amap ->
                amap << ['id': it?.id]
            }
            rds << b
        }
        return rds
    }
}
